//
//  WD_MyPlayer.m
//  BUDING
//
//  Created by HanWoonYong on 16/4/5.
//  Copyright © 2016年 HanWoonYong. All rights reserved.
//

#import "WD_MyPlayer.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>
#import <AVKit/AVKit.h>
#import "WD_MyPlayerMaskView.h"
#define WIDTH [UIScreen mainScreen].bounds.size.width
#define HEIGHT [UIScreen mainScreen].bounds.size.height
#define BOUNDS [UIScreen mainScreen].bounds

typedef NS_ENUM(NSInteger, GestureDirection) {
    GestureDirectionHorizontalMoved, // 横向滑动
    GestureDirectionVerticalMoved    // 纵向滑动
};

typedef NS_ENUM(NSInteger, WDPlayerState) {
    WDPlayerStateBuffering, // 缓存中
    WDPlayerStatePlaying,   // 播放中
    WDPlayerStateStop,      // 停止播放
    WDPlayerStatePause      // 暂停播放
};

@interface WD_MyPlayer()<UIGestureRecognizerDelegate>
//@property (nonatomic, strong) AVPlayerLayer *playerLayer;
@property (nonatomic, strong) NSTimer *sliderTimer;
@property (nonatomic, assign) BOOL touch;
@property (nonatomic, assign) BOOL isplay;
@property (nonatomic, assign) BOOL drag;
@property (nonatomic, assign) WDPlayerState playState;// 定义属性来保存枚举
@property (nonatomic, assign) GestureDirection gestureDirection;
@property (nonatomic, assign) NSInteger isSmall;
@property (nonatomic, assign) CGRect smallFram;
@property (nonatomic, assign) CGRect bigFram;
@end

@implementation WD_MyPlayer

- (instancetype)initWithMyPlayFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        self.frame = frame;
        self.smallFram = self.frame;
        self.bigFram = CGRectMake(0, 0, WIDTH, HEIGHT);
        self.maskView = [[WD_MyPlayerMaskView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        self.player = [WD_MyAVPlayer shareAVPlayer];
        [self.player initWithPlayLayerFrame:self.bounds MaskView:self.maskView];
        [self.layer addSublayer:self.player.playerLayer];
        [self.maskView.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        self.maskView.playButton.selected = YES;
        [self.maskView.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.maskView.bigButton addTarget:self action:@selector(bigButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        // slider开始滑动
        [self.maskView.slider addTarget:self action:@selector(progressSliderBegin:) forControlEvents:UIControlEventValueChanged];
        [self addSubview:self.maskView];
        self.sliderTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(sliderTimerAction) userInfo:nil repeats:YES];
        
        //点击屏幕控件消失
        //开通用户交互
        self.player.usesExternalPlaybackWhileExternalScreenIsActive = YES;
        self.tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        self.tap.numberOfTapsRequired = 1;
        // 添加快进快退音量的滑动手势
        self.pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureRecognizerAction:)];
        self.pan.delegate = self;
        
        // app进入后台
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillResignActiveNotification) name:UIApplicationWillResignActiveNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActiveNotification) name:UIApplicationDidBecomeActiveNotification object:nil];
        
        [self listeningRotating];
        [self addGestureRecognizer:self.tap];
        [self addGestureRecognizer:self.pan];
        [self.sliderTimer fire];
    }
    return self;
}

- (void)setUrl:(NSString *)url {
    self.player.url = url;
}

- (NSTimeInterval)availableTime {
    NSArray *loadTimeRange = [[self.player currentItem] loadedTimeRanges];
    CMTimeRange timeRange = [loadTimeRange.firstObject CMTimeRangeValue];// 获取缓冲区域
    float startSecond = CMTimeGetSeconds(timeRange.start);
    float durationSecond = CMTimeGetSeconds(timeRange.duration);
    NSTimeInterval result = startSecond + durationSecond;// 计算缓冲总进度
    return result;
}


- (void)tapAction:(UITapGestureRecognizer *) sender {
    if (self.touch == YES) {
        self.maskView.hidden = NO;
        self.touch = NO;
    } else if (self.touch == NO) {
        self.maskView.hidden = YES;
        self.touch = YES;
    }
    
}

- (void)panGestureRecognizerAction:(UIPanGestureRecognizer *)pan {
    // 我们要响应水平移动和垂直移动
    // 根据上次和本次移动的位置，算出一个速率的point
    CGPoint velocity = [pan velocityInView:self];
    // 判断是水平划动还是垂直滑动
    switch (pan.state) {
        case UIGestureRecognizerStateBegan:{
            CGFloat x = fabs(velocity.x);
            CGFloat y = fabs(velocity.y);
            if (x > y) {
                self.gestureDirection = GestureDirectionHorizontalMoved;
            } else if (x < y) {
                self.gestureDirection = GestureDirectionVerticalMoved;
            }
        }
            break;
        case UIGestureRecognizerStateChanged:{
            switch (self.gestureDirection) {
                case GestureDirectionHorizontalMoved:{
                    [self horizontalMoved:velocity.x];
                    [self progressSliderBegin:self.maskView.slider];
                }
                    break;
                    
                default:
                    break;
            }
        }
            break;
        default:
            break;
    }
    
}

- (void)horizontalMoved:(CGFloat)value {
    self.maskView.slider.value += value / 10000;
}

- (void)verticalMoved:(CGFloat)value {
    
}

// slider开始滑动
- (void)progressSliderBegin:(UISlider *)slider {
    CGFloat total = (CGFloat)self.player.playItem.duration.value / self.player.playItem.duration.timescale;
    //    跳转到的时间 总长／帧数
    //    每秒多少帧（fps）
    [self.player seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.duration.value / self.player.currentItem.duration.timescale * self.maskView.slider.value, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
        
    }];
    NSLog(@"%f", total);
    
}

- (void)sliderTimerAction {
    self.maskView.slider.value = CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration);
    CMTime presentTime = self.player.currentItem.currentTime;
    CMTime totalTime = self.player.currentItem.duration;
    CGFloat presentFloatTim = (CGFloat)presentTime.value/presentTime.timescale;
    CGFloat totalFloatTim = (CGFloat)totalTime.value / totalTime.timescale;
    NSDate *presentDate = [NSDate dateWithTimeIntervalSince1970:presentFloatTim];
    NSDate *totalDate = [NSDate dateWithTimeIntervalSince1970:totalFloatTim];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    if (totalFloatTim / 3600 >= 1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    }else {
        [formatter setDateFormat:@"m:ss"];
    }
    NSString *presentStrTime = [formatter stringFromDate:presentDate];
    NSString *totalStrTime = [formatter stringFromDate:totalDate];
    self.maskView.playTime.text = [NSString stringWithFormat:@"%@/%@", presentStrTime, totalStrTime];
    NSTimeInterval timeInterval = [self availableTime]; // 计算缓冲进度
    CMTime duration = self.player.playItem.duration;
    CGFloat totle = CMTimeGetSeconds(duration);
    [self.maskView.progressView setProgress:timeInterval / totle animated:YES];
    
}


// 播放按钮事件
- (void)playButtonAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    if (sender.selected) {
        [self.player pause];
        [self.maskView.playButton setBackgroundImage:[UIImage imageNamed:@"Image-2"] forState:UIControlStateNormal];
        self.playState = WDPlayerStatePause;
        NSLog(@"暂停啦");
    } else {
        [self.player play];
        [self.maskView.playButton setBackgroundImage:[UIImage imageNamed:@"Image-3"] forState:UIControlStateNormal];
        self.playState = WDPlayerStatePlaying;
        NSLog(@"播放啦");
    }
    
}

- (void)interfaceOrientation:(UIInterfaceOrientation)orientation {
    // - (BOOL)respondsToSelector:(SEL)aSelector; 判断是否有用某个名字命名的方法
    
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector = NSSelectorFromString(@"setOrientation:"); // 指定方法
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]]; // 签名函数（调用方法）
        [invocation setSelector:selector]; // 设置selector
        [invocation setTarget:[UIDevice currentDevice]]; // 设置目标
        int val = orientation;
        [invocation setArgument:&val atIndex:2];
        [invocation invoke]; // 消息调用
    }
    
    
}


#pragma mark - 翻转页面事件
- (void)bigButtonAction:(UIButton *)sender {
    NSLog(@"点击放大按钮啦");
    sender.selected = !sender.selected; // 每次点击都会改变按钮状态
    [self interfaceOrientation:(sender.selected==YES)?UIInterfaceOrientationLandscapeRight:UIInterfaceOrientationPortrait];
    
}

#pragma mark - 监听屏幕旋转方向
- (void)listeningRotating {
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationChange) name:UIDeviceOrientationDidChangeNotification object:nil];
}

#pragma mark - 屏幕旋转通知
- (void)deviceOrientationChange {
    UIDeviceOrientation orientation = [UIDevice currentDevice].orientation;
    UIInterfaceOrientation interfaceOrientation = (UIInterfaceOrientation)orientation;
    [self transformScreenDirection:interfaceOrientation];
}

#pragma mark - 屏幕旋转
- (void)transformScreenDirection:(UIInterfaceOrientation)direction {
    if (direction == UIInterfaceOrientationPortrait) {
        self.frame = CGRectMake(0, 0, 414, 300);
        [self.maskView.bigButton setBackgroundImage:[UIImage imageNamed:@"Image-5"] forState:UIControlStateNormal];
        NSLog(@"缩小啦");
    } else if (direction == UIInterfaceOrientationLandscapeRight) {
        self.frame = CGRectMake(0, 0, WIDTH, HEIGHT);
        [self.maskView.bigButton setBackgroundImage:[UIImage imageNamed:@"Image-7"] forState:UIControlStateNormal];
        NSLog(@"放大啦");
    }
    
}


- (void)backButtonAction:(UIButton *)sender {
    self.backBlock();
}

- (void)layoutSubviews {
    [super layoutSubviews];
    [UIApplication sharedApplication].statusBarHidden = NO;
    self.player.playerLayer.frame = self.bounds;
    self.maskView.frame = self.bounds;
}

//单独定制白色电池条
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

- (void)applicationWillResignActiveNotification {
    [self.player pause];
}

- (void)applicationDidBecomeActiveNotification {
    if (self.playState == WDPlayerStatePlaying) {
        [self.player play];
    }
}







/*
 // Only override drawRect: if you perform custom drawing.
 // An empty implementation adversely affects performance during animation.
 - (void)drawRect:(CGRect)rect {
 // Drawing code
 }
 */

@end
